package cn.anecansaitin.whimsy.common.network;

import cn.anecansaitin.whimsy.Whimsy;
import cn.anecansaitin.whimsy.common.item.RockSceptre;
import cn.anecansaitin.whimsy.common.register.ModItems;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.neoforged.neoforge.network.handling.PlayPayloadContext;

import java.util.Optional;

public record RockSceptreKeyInput(boolean mouseButtonLeftClick,
                                  boolean mouseButtonRightClick) implements CustomPacketPayload {
    public static final ResourceLocation ID = Whimsy.resource("rock_sceptre_key_input");
    public static final ServerHandler HANDLER = new ServerHandler();

    public RockSceptreKeyInput(FriendlyByteBuf buffer) {
        this(buffer.readBoolean(), buffer.readBoolean());
    }

    @Override
    public void write(FriendlyByteBuf friendlyByteBuf) {
        friendlyByteBuf.writeBoolean(mouseButtonLeftClick);
        friendlyByteBuf.writeBoolean(mouseButtonRightClick);
    }

    @Override
    public ResourceLocation id() {
        return ID;
    }

    public static class ServerHandler {
        private ServerHandler() {
        }

        public void handle(RockSceptreKeyInput data, PlayPayloadContext context) {
            context.workHandler().submitAsync(() -> {
                Optional<Player> player = context.player();

                if (player.isEmpty()) {
                    return;
                }

                ItemStack item = player.get().getMainHandItem();

                if (item.is(ModItems.ROCK_SCEPTRE.get())) {
                    ((RockSceptre) item.getItem()).onKeyInput(item, data);
                }
            });
        }
    }
}
